package com.dd.ent.car.ui.user;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;

import com.dd.ent.car.R;
import com.dd.ent.car.common.bean.User;
import com.dd.ent.car.common.config.UIConfig;
import com.dd.ent.car.common.util.ImageUtils;
import com.dd.ent.car.common.util.SDCardUtil;
import com.dd.ent.car.common.util.ScreenUtils;
import com.dd.ent.car.service.note.NoteService;
import com.dd.ent.car.service.user.UserService;
import com.dd.ent.car.ui.BaseActivity;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.pp.ent.base.log.MLog;
import com.pp.ent.core.manage.UIHandler;
import com.pp.ent.view.annotation.ContentView;
import com.pp.ent.view.annotation.Inject;
import com.pp.ent.view.annotation.OnClick;
import com.pp.ent.view.annotation.ViewInject;
import com.qiniu.android.http.ResponseInfo;

import java.util.ArrayList;

import me.iwf.photopicker.PhotoPicker;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by dengqu on 2018/4/2.
 */
@ContentView(R.layout.activity_edit_user)
public class EditUserActivity extends BaseActivity {

    @ViewInject(R.id.user_account_portrait)
    private UserAccountItem mAvathorItem;

    @ViewInject(R.id.user_account_nickname)
    private UserAccountItem mNickNameItem;

    @ViewInject(R.id.user_account_sexuality)
    private UserAccountItem mSexItem;

    @ViewInject(R.id.user_account_phone)
    private UserAccountItem mPhoneItem;

    @ViewInject(R.id.user_account_job)
    private UserAccountItem mJobItem;

    @ViewInject(R.id.user_account_car_number)
    private UserAccountItem mCarNumberItem;

    @ViewInject(R.id.user_account_car_type)
    private UserAccountItem mCarTypeItem;

    @ViewInject(R.id.user_account_car_project)
    private UserAccountItem mCarProjectItem;

    @Inject
    private UserService userService;
    @Inject
    private NoteService noteService;

    private ProgressDialog insertDialog;
    private Subscription subsInsert;
    private boolean mIsClearPortraitCash;
    private String smallImagePath;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, EditUserActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
    }

    private void initData() {
        mAvathorItem.setAccountItemName("头像");
        mNickNameItem.setAccountItemName("昵称");
        mSexItem.setAccountItemName("性别");
        mPhoneItem.setAccountItemName("手机号");
        ImageLoader.getInstance().displayImage(userService.getAvathor(), mAvathorItem.getAccountItemTipPic());
        mNickNameItem.setItemTipText(userService.getUser().getUserName());
        mSexItem.setItemTipText(userService.getUser().getSexText());
        mPhoneItem.setItemTipText(userService.getUser().getPhoneNumber());

        insertDialog = new ProgressDialog(this);
        insertDialog.setMessage("正在插入图片...");
        insertDialog.setCanceledOnTouchOutside(false);


    }

    @OnClick({R.id.user_account_portrait})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_account_portrait:
                callGallery();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        mIsClearPortraitCash = true;
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                if (requestCode == 1) {
                    //处理调用系统图库
                } else if (requestCode == PhotoPicker.REQUEST_CODE) {
                    //异步方式插入图片
                    insertImagesSync(data);
                }
            }
        }
    }


    private void insertImagesSync(final Intent data) {
        insertDialog.show();
        subsInsert = Observable.create(new Observable.OnSubscribe<Bitmap>() {
            @Override
            public void call(Subscriber<? super Bitmap> subscriber) {
                try {
                    int width = ScreenUtils.getScreenWidth(EditUserActivity.this);
                    int height = ScreenUtils.getScreenHeight(EditUserActivity.this);
                    ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                    //可以同时插入多张图片
                    if (photos != null && photos.size() > 0) {
                        //Log.i("NewActivity", "###path=" + imagePath);
                        String imagePath = photos.get(0);
                        Bitmap bitmap = ImageUtils.getSmallBitmap(imagePath, width, height);//压缩图片
                        //bitmap = BitmapFactory.decodeFile(imagePath);
                        smallImagePath = SDCardUtil.saveToSdCard(bitmap);
                        String avthorUrl = userService.getAvathor();
                        if (smallImagePath != null) {
                            ResponseInfo responseInfo = noteService.syncSumbitFile(smallImagePath);
                            MLog.debug("getEditData", responseInfo.path);
                            avthorUrl = "http://quydbezgk.hn-bkt.clouddn.com/" + responseInfo.response.optString("hash");
                        }
                        User user = userService.getUser();
                        user.setAvathor(avthorUrl);
                        userService.refreshUser(user);
                        userService.update();
                        subscriber.onNext(bitmap);
                    }
                    subscriber.onCompleted();
                } catch (Exception e) {
                    e.printStackTrace();
                    subscriber.onError(e);
                }
            }
        })
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())//生产事件在io
                .observeOn(AndroidSchedulers.mainThread())//消费事件在UI线程
                .subscribe(new Observer<Bitmap>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(Bitmap bitmap) {
                        mAvathorItem.setImageBitmap(bitmap);
                    }
                });
    }

    /**
     * 调用图库选择
     */
    private void callGallery() {
        //调用第三方图库选择
        PhotoPicker.builder()
                .setPhotoCount(1)//可选择图片数量
                .setShowCamera(true)//是否显示拍照按钮
                .setShowGif(true)//是否显示动态图
                .setPreviewEnabled(true)//是否可以预览
                .start(this, PhotoPicker.REQUEST_CODE);
    }

    @UIHandler(UIConfig.UPDATE_NAME_SEX_SUCCESS)
    public void updateNameSexResponse() {
        insertDialog.dismiss();
        showToast("设置头像成功");
    }

    @UIHandler(UIConfig.UPDATE_NAME_SEX_FAIL)
    public void updateNameSexFail() {
        insertDialog.dismiss();
        showToast("设置头像失败");
    }

}
